import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { SalesmanRoleSettingService } from '@core/routes-services/salesman-role-setting.service';

@Component({
  selector: 'app-market-salesman-role-setting',
  templateUrl: './role-setting.component.html',
})
export class MarketSalesmanRoleSettingComponent implements OnInit {
  @Input() role;
  entity: any = {};
  validateForm: FormGroup;

  isLoading: boolean = false;

  constructor(private fb: FormBuilder,
              private salesmanRoleSettingService:SalesmanRoleSettingService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.initValidateForm();
    this.initRoleSetting();
  }
  initRoleSetting(){
    if(this.role != 1){
      this.salesmanRoleSettingService.getByType(this.role).then((res) => {
        console.log(res)
        if (res.status.toString().startsWith("20")) {
          this.entity = res.data;
          this.initValidateForm();
        } else {
          this.message.warning(res.message);
        }
      },error =>{
        this.message.error(error.message ? error.message : error.error)
      });
    }
  }
  initValidateForm() {
    //角色: 1-业务员，2-渠道商，3-门店，4-代理
    this.validateForm = this.fb.group({
      type: [this.entity.type, [Validators.required]],
      name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
      beAutomatic: [this.entity.beAutomatic, [Validators.required]],
      teamNum: [this.entity.teamNum, [Validators.required]],
      teamAchievement: [this.entity.teamAchievement, [Validators.required]],
    });
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.salesmanRoleSettingService.update(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.entity = res.data;
          this.initValidateForm()
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }


}
